//
//  LKBoTongFeedbackWebViewController+Camera.m
//  iOS-BTong-ApplicationCenter
//
//  Created by maqz on 2018/4/4.
//  Copyright © 2018年 毛毛驴. All rights reserved.
//

#import "LKBoTongFeedbackWebViewController+Camera.h"
#import <CommonCrypto/CommonDigest.h>
#import "TZImagePickerController.h"
#import "LEEAlert.h"
#import "FBCameraHomeViewController.h"
#import "FBHUD.h"

@interface LKBoTongFeedbackWebViewController () <TZImagePickerControllerDelegate>
@end

@implementation LKBoTongFeedbackWebViewController (Camera)

NSString *BotongApplicationCenterCameraJSHandler = @"BotongApplicationCenterCameraJSHandler";

- (void)scriptCameraMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:BotongApplicationCenterCameraJSHandler]) {
        
        NSDictionary *params = message.body[scriptParams];
        if (!params || ![params isKindOfClass:[NSDictionary class]]) {
            return;
        }
        
        // 是否从签到跳转过来
        BOOL isSignIn = [params[@"sign"] ?: @0 boolValue];
        
        LEEAlertConfig *alert = [LEEAlert actionsheet];
        LEEAlertConfigModel *config = alert.config;
        config.LeeAction(@"相机", ^{
            FBCameraHomeViewController *cameraVC = [[FBCameraHomeViewController alloc] init];
            cameraVC.cameraType = FBCameraTypePhoto;
            __weak __typeof(self)weakSelf = self;
            [cameraVC cameraPickerImageComplate:^(UIImage *image, FBCameraHomeViewController *vc) {
                [weakSelf uploadImage:image];
            } videoComplate:nil];
            [self presentViewController:cameraVC animated:YES completion:nil];
        });
        
        // 签到不能从相册选择图片
        if (!isSignIn) {
            config.LeeAction(@"从相册中选择", ^{
                TZImagePickerController *imagePickerController = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
                imagePickerController.allowPickingVideo = NO;
                [self presentViewController:imagePickerController animated:YES completion:nil];
            });
        }
        
        config.LeeCancelAction(@"取消", nil);
        config.LeeShow();
    }
}


// MARK: Image picker delegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    for (UIImage *image in photos) {
        [self uploadImage:image];
    }
}


- (void)uploadImage:(UIImage *)image {
    
    kHUDLoading(self.view);
  /*
    NSString *currentTimeStamp = [@([[NSDate date] timeIntervalSince1970]) stringValue];
    
    NSString *url = [NSString stringWithFormat:@"%@/file/upload-pic", [[MBMediator sharedInstance] Config_commonFileAPI]];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
    NSString *name = [[currentTimeStamp stringByAppendingString:@"location"] stringByAppendingString:@".jpg"];
    NSDictionary *params = @{@"appKey" : @"boTong2.x",
                             @"ext" : @"jpg",
                             @"fileSize" : @(imageData.length),
                             @"md5" : [currentTimeStamp stringByAppendingString:@"2231asdas"]
                             };

    __weak __typeof(self)weakself = self;
    [ApiUtil uploadWithArguments:params requestURL:url fileData:imageData name:@"file" fileName:name mimeType:@"image/jpg" httpHeaders:@{@"Content-Type":@"multipart/form-data"} progress:^(NSProgress *progress) {

    } success:^(NSDictionary *jsonObject) {
        __strong __typeof(weakself)strongSelf = weakself;

        kHUDEnd(self.view);
        if ([jsonObject[@"statusCode"] isEqual:@200]) {
            NSDictionary *data = jsonObject[@"data"];
            if (!data || ![data isKindOfClass:[NSDictionary class]]) {
                return;
            }
            [strongSelf evaluateJavaScript:data];
        }
    } failure:^(NSError *error) {
        kHUDEnd(self.view);
        kToast(@"网络异常，请稍后再试");
    }];
   */
    kHUDEnd(self.view);
}

- (void)evaluateJavaScript:(NSDictionary *)params {
    NSDictionary *body = self.scriptMessages[BotongApplicationCenterCameraJSHandler];
    NSString *callbackMethod = body[scriptCallbackMethod];
    if (!callbackMethod || !callbackMethod.length) {
        return;
    }
    
    NSString *fileJson = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
    fileJson = [fileJson stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    fileJson = [fileJson stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSString *scriptString = [NSString stringWithFormat:@"%@(%@)", callbackMethod, fileJson];
    [self evaluateJavaScript:scriptString completionHandler:nil];
}

- (NSString *)md5WithData:(NSData *)data {

    CC_MD5_CTX md5;
    CC_MD5_Init(&md5);
    CC_MD5_Update(&md5, data.bytes,(CC_LONG)data.length);
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(result, &md5);
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [resultStr appendFormat:@"%02X",result[i]];
    }
    return resultStr;
}
@end
